package vns.server;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import vns.client.service.RuleSetService;
import vns.server.domain.RuleSet;
import vns.shared.ObjectTypeDTO;
import vns.shared.RuleSetDTO;

import com.google.appengine.api.datastore.Key;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

@SuppressWarnings("serial")
public class RuleSetServiceImpl extends RemoteServiceServlet implements RuleSetService{

	@Override
	public RuleSetDTO Create(RuleSetDTO rulesetDTO) {
		PersistenceManager pm=PMF.get().getPersistenceManager();
		RuleSet action=null;
		try{
			action=new RuleSet(rulesetDTO);
			pm.makePersistent(action);
		}finally{
			pm.close();
		}
		return action.toDTO();
	}

	@Override
	public boolean Remove(Key id) {
		PersistenceManager pm=PMF.get().getPersistenceManager();
		try{
			RuleSet action= pm.getObjectById(RuleSet.class,id);
			if(action!=null){
				pm.deletePersistent(pm.getObjectById(RuleSet.class,id));
			}
		}finally{
			pm.close();
		}
		return true;
	}

	@Override
	public RuleSetDTO Loadbyid(Key id) {
		PersistenceManager pm=PMF.get().getPersistenceManager();
		RuleSetDTO actionDTO=null;
		try{
			RuleSet action = pm.getObjectById(RuleSet.class,id);	
			actionDTO=action.toDTO();
		}finally{
			pm.close();
		}
		return actionDTO;
	}

	@Override
	public RuleSetDTO Update(RuleSetDTO rulesetDTO) {
		PersistenceManager pm=PMF.get().getPersistenceManager();
		RuleSet action=null;
		try{
			action=pm.getObjectById(RuleSet.class,rulesetDTO.getId());
			action.updatefromDTO(rulesetDTO);
		}finally{
			pm.close();
		}
		
		return action.toDTO();
	}

	@Override
	public ArrayList<RuleSetDTO> Loadall() {
		ArrayList<RuleSetDTO> listactionDTO= new ArrayList<RuleSetDTO>();
		PersistenceManager pm=PMF.get().getPersistenceManager();
		Query q=pm.newQuery(RuleSet.class);
		try{
		List<RuleSet> res=(List<RuleSet>) q.execute();
		for(RuleSet actiontype:res){
			listactionDTO.add(actiontype.toDTO());
		}
		}finally{
			pm.close();
		}
		return listactionDTO;
	}

	@Override
	public void Updateall(List<RuleSetDTO> listNew) {
		ArrayList<RuleSetDTO> listOld = this.Loadall();
		for (RuleSetDTO element : listNew) {
			if (!containInList(listOld,element)) {
				element = this.Create(element);
			} else {
				this.Update(element);
			}
		}
		for (RuleSetDTO element : listOld) {
			if (!containInList(listNew,element)) {
				this.Remove(element.getId());
			}
		}
		
	}
	
	private boolean containInList(List<RuleSetDTO> list,
			RuleSetDTO element) {
		if (element.getId() == null)
			return false;
		for (RuleSetDTO ruleDTO : list) {
			if (ruleDTO.getId().equals(element.getId()))
				return true;
		}
		return false;
	}

}
